package logic

import (
	"context"
	"customer/model/mysql"
	"customer/model/redis"
	"customer/pkg"
	"fmt"

	"customer/userrpc/internal/svc"
	"customer/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *userrpc.UserUpdateRequest) (*userrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line

	get := redis.Client.Get("captchaupdate" + in.Account)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}

	cmd := redis.Client.Get("sendSmsupdate" + in.Tel)
	if cmd.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}

	if in.Password1 != in.Password2 {
		return nil, fmt.Errorf("新密码与确认密码不一致，请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Where("Account=?", in.Account).First(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("该用户不存在，请重新输入")
	}
	if user.Password != pkg.PwdMd5(in.Password) {
		return nil, fmt.Errorf("旧密码错误，请重新输入")
	}
	if user.Tel != in.Tel {
		return nil, fmt.Errorf("手机号错误，请重新输入")
	}
	if in.Password == in.Password1 {
		return nil, fmt.Errorf("旧密码与新密码不能一致，请重新输入")
	}
	user.Password = pkg.PwdMd5(in.Password1)
	mysql.DB.Debug().Updates(&user)
	redis.Client.Del("captchaupdate" + in.Account)
	redis.Client.Del("sendSmsupdate" + in.Tel)

	return &userrpc.UserUpdateResponse{Id: int64(user.ID)}, nil
}
